import { SETUSERINFO, LOGOUT } from './actionTypes'
let defaultState = {
 
}

const noState = {
  userInfo:{
    userName:'',
    avatar:'',
    role:''
  }
}
// 初始 读 缓存 设置 redux  userInfo token
const userInfo = localStorage.getItem('userInfo')?JSON.parse(localStorage.getItem('userInfo')):noState;

defaultState.userInfo = userInfo

// token处理
const token = localStorage.getItem('token')?localStorage.getItem('token'):'';
defaultState.token = token

const reducer  = (state = defaultState,action)=>{
  let newState = JSON.parse(JSON.stringify(state))
 
  switch (action.type){
    //设置用户信息
    case SETUSERINFO:
      newState.userInfo = action.userInfo;
      newState.token = action.token;
      break;
    case LOGOUT:
      newState.token = ""
      newState.userInfo = {}
    default: break;
  }
  // 数据更新 同步storage
  localStorage.setItem('userInfo',JSON.stringify(newState.userInfo))
  localStorage.setItem('token',newState.token)
  return newState
}

export default reducer